//
//  BKLineChartView.m
//  智能备考学习
//
//  Created by 盛超 on 2018/1/22.
//  Copyright © 2018年 盛超. All rights reserved.
//

#import "BKLineChartView.h"
//#define bounceX 20
#define bounceX 0
#define bounceY 30
#define PaddingWidth 15
//#define YMax 10000

@interface BKLineChartView ()<CAAnimationDelegate>

@property (nonatomic,strong) NSMutableArray *onePointArr;
@property (nonatomic,strong) NSMutableArray *secondPointArr;
@property (nonatomic,strong) NSMutableArray *oneYValues;
@property (nonatomic,strong) NSMutableArray *secondYValues;
@property (nonatomic,strong) UIButton *scoreBtn;

@end

@implementation BKLineChartView 

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        _YMax = 100;
        _YMin = 0;
        self.backgroundColor = [UIColor clearColor];
    }
    return self;
}

#pragma mark - 创建X轴数据
- (void)createLabelX {
    CGFloat month = self.XdateArr.count;
    for (NSInteger i = 0; i<month; i++) {
        
        UILabel *labelX = [[UILabel alloc] initWithFrame:CGRectMake(0+i*50*ScalesW,self.frame.size.height-bounceY,40*ScalesW,ScalesW*bounceY/2)];
        labelX.tag = 1000+i;
        labelX.text = self.XdateArr[i];
        //labelX.backgroundColor = [UIColor blueColor];
        labelX.text = [labelX.text stringByReplacingOccurrencesOfString:@"-" withString:@"."];
        if (labelX.text.length>6) {
            labelX.text = [labelX.text substringFromIndex:5];
        }
        labelX.font = [UIFont systemFontOfSize:10*ScalesW];
        labelX.textColor = [UIColor colorWithHex:0xcfcfcf];
        labelX.textAlignment = NSTextAlignmentCenter;
        
        [self addSubview:labelX];
        
//        if (i==0) {
//            CGFloat width = self.contentSize.width;
//            if (self.contentSize.width<self.width) {
//                width = self.width;
//            }
//            UILabel *labelXname = [[UILabel alloc] initWithFrame:CGRectMake(width-bounceX-20,labelX.y,40,bounceY/2)];
//            labelXname.font = [UIFont systemFontOfSize:10];
//            labelXname.textColor = [UIColor colorWithHex:0xcfcfcf];
//            labelXname.textAlignment = NSTextAlignmentLeft;
//            labelXname.text = @"日期";
//            [self addSubview:labelXname];
//        }
    }
    
    for(NSInteger i = 0;i<5;i++) {
        UILabel *line = [[UILabel alloc] initWithFrame:CGRectMake(0,(self.frame.size.height - 2 * bounceY)/5 *i + bounceY,self.contentSize.width, 0.5)];
        line.backgroundColor = [UIColor colorWithR:230 g:230 b:230 a:0.5];
        [self addSubview:line];
    }
    
}

#pragma mark - 创建Y轴数据
- (void)createlabelY {
    //    [self handleMaxY:_Yarr];
    //    [self handelMinY:_Yarr];
  
    CGFloat differenceYValue = _YMax - _YMin;
    
    for (NSInteger i = 0; i<5; i++) {
        UILabel *labelY = [[UILabel alloc] initWithFrame:CGRectMake(0, (self.frame.size.height - 2 * bounceY)/5 *i + bounceY-9, 18, bounceY/2.0)];
        labelY.tag = 2000+i;
        labelY.text = [NSString stringWithFormat:@"%d",(int)(differenceYValue/5 *(5-i))];
        labelY.font = [UIFont systemFontOfSize:10];
        labelY.textColor = [UIColor colorWithHex:0xcfcfcf];
        labelY.textAlignment = NSTextAlignmentRight;
        //labelY.backgroundColor = [UIColor blueColor];
        [self addSubview:labelY];
        if (i==0) {
            UILabel *labelYname = [[UILabel alloc] initWithFrame:CGRectMake(0,labelY.y-20,40,20)];
            labelYname.font = [UIFont systemFontOfSize:10];
            labelYname.textColor = [UIColor colorWithHex:0xcfcfcf];
            labelYname.textAlignment = NSTextAlignmentCenter;
            labelYname.text = @"能力值";
            [self addSubview:labelYname];
        }
        UILabel *line = [[UILabel alloc] initWithFrame:CGRectMake(bounceX,(self.frame.size.height - 2 * bounceY)/5 *i + bounceY,self.frame.size.width-bounceX*2, 0.5)];
        line.backgroundColor = [UIColor colorWithR:230 g:230 b:230 a:0.5];
        [self addSubview:line];
    }
}

//绘制图表
- (void)drawRect:(CGRect)rect {
//    CGContextRef context = UIGraphicsGetCurrentContext();
//    CGContextSetLineWidth(context, 0.5);
//    CGContextSetRGBStrokeColor(context,207.0/255,207.0/255,207.0/255,0.5);
// //   NSInteger x = 60;
////    CGContextMoveToPoint(context,x,0);
////    CGContextAddLineToPoint(context, x, rect.size.height-bounceY);//Y轴
////    CGContextAddLineToPoint(context, rect.size.width, rect.size.height-bounceY);//X轴
//    CGContextMoveToPoint(context,50,10);
//    CGContextAddLineToPoint(context,50, rect.size.height-bounceY);//Y轴
//    CGContextAddLineToPoint(context,rect.size.width+50, rect.size.height-bounceY);//X轴
//    CGContextStrokePath(context);
}

- (void)drawLine {
    NSArray *onearr = [self drawLineDict:self.OneXDictionary];
    self.onePointArr = [NSMutableArray arrayWithArray:onearr.firstObject];
    self.oneYValues =  [NSMutableArray arrayWithArray:onearr.lastObject];

    NSArray *secondarr = [self drawLineDict:self.SecondXDictionary];
    self.secondPointArr = [NSMutableArray arrayWithArray:secondarr.firstObject];
    self.secondYValues = [NSMutableArray arrayWithArray:secondarr.lastObject];
}

- (NSArray*)drawLineDict:(NSDictionary*)Xdictionary {
    UIBezierPath * onepath = [[UIBezierPath alloc]init];
    NSMutableArray * pointArr = [NSMutableArray array];
    NSMutableArray * Yvalues = [NSMutableArray array];
    
   for (NSInteger i = 0; i<self.XdateArr.count; i++) {
       UILabel *label = (UILabel*)[self viewWithTag:1000+i];//根据横坐标上的label获取x坐标的值
       NSString *dateString = self.XdateArr[i];
       NSString *oneY = [Xdictionary objectForKey:dateString];
       NSInteger oneCount = 0;
       if (oneY!=nil) {
           [Yvalues addObject:oneY];
           CGPoint point1 = CGPointMake(label.frame.origin.x+label.frame.size.width/2, bounceY+(_YMax-oneY.floatValue) /(_YMax-_YMin) * (self.frame.size.height - bounceY*2));
           if (oneCount==0) {
               [onepath moveToPoint:point1];
           } else {
               CGPoint from = ((NSValue*)(pointArr[i-1])).CGPointValue;
               CGPoint to = point1;
               CGPoint midPoint = [self midPointBetweenPoint1:from andPoint2:to];
               [onepath addQuadCurveToPoint:midPoint controlPoint:[self controlPointBetweenPoint1:midPoint andPoint2:from]];
               [onepath addQuadCurveToPoint:to controlPoint:[self controlPointBetweenPoint1:midPoint andPoint2:to]];
           }
           [pointArr addObject:[NSValue valueWithCGPoint:point1]];
           oneCount++;
       }
    }
    
    CAShapeLayer *lineChartLayer = [CAShapeLayer layer];
    lineChartLayer.strokeColor = [UIColor yellowColor].CGColor;
    lineChartLayer.fillColor = [[UIColor clearColor] CGColor];
    // 默认设置路径宽度为0，使其在起始状态下不显示
    lineChartLayer.lineWidth = 1;
    lineChartLayer.lineCap = kCALineCapRound;
    lineChartLayer.lineJoin = kCALineJoinRound;
    lineChartLayer.path = onepath.CGPath;
   // [self doAnimationWithLayer:oneLayer];
    [self.layer addSublayer:lineChartLayer];//直接添加导视图上
    
    return @[pointArr,Yvalues];
}

//计算绘制贝塞尔曲线controlPoint
- (CGPoint)controlPointBetweenPoint1:(CGPoint)point1 andPoint2:(CGPoint)point2 {
    CGPoint controlPoint = [self midPointBetweenPoint1:point1 andPoint2:point2];
    CGFloat diffY = abs((int) (point2.y - controlPoint.y));
    if (point1.y < point2.y)
        controlPoint.y += diffY;
    else if (point1.y > point2.y)
        controlPoint.y -= diffY;
    return controlPoint;
}

- (CGPoint)midPointBetweenPoint1:(CGPoint)point1 andPoint2:(CGPoint)point2 {
    return CGPointMake((point1.x + point2.x) / 2, (point1.y + point2.y) / 2);
}


//点和数值
- (void)addPointCircle {
    
    for (NSInteger i = 0; i<self.onePointArr.count; i++) {
        CGPoint point = [self.onePointArr[i] CGPointValue];
        LSCircleBtn * circle = [[LSCircleBtn alloc] initWithFrame:CGRectMake(point.x-5,point.y-5,10,10)];
        circle.userInteractionEnabled = YES;
        circle.backgroundColor = [UIColor whiteColor];
        circle.layer.cornerRadius = 5;
        circle.layer.borderWidth = 2;
        circle.layer.borderColor = _lineChartBackgroundColor.CGColor;
        circle.layer.masksToBounds = YES;
        circle.index = 0;
        circle.tag = 40000 + ((NSNumber*)self.oneYValues[i]).integerValue;
        [self addSubview:circle];
        [circle addTarget:self action:@selector(showScore:) forControlEvents:UIControlEventTouchUpInside];
       // [circle.layer addAnimation:[self moveYtime:0.5 Y:[NSNumber numberWithFloat:point.y-5] Rep:1] forKey:nil];
        circle.alpha = 0;
        [UIView animateWithDuration:0.5 animations:^{
            circle.alpha = 0.25;
        } completion:^(BOOL finished) {
            circle.alpha = 0.5;
            [UIView animateWithDuration:0.5 animations:^{
                circle.alpha = 0.75;
            } completion:^(BOOL finished) {
                circle.alpha = 1;
            }];
        }];
    }
    
    for (NSInteger i = 0; i<self.secondPointArr.count; i++) {
        CGPoint point = [self.secondPointArr[i] CGPointValue];
        LSCircleBtn * circle = [[LSCircleBtn alloc]initWithFrame:CGRectMake(point.x-5,point.y-5,10,10)];
        circle.userInteractionEnabled = YES;
        circle.backgroundColor = [UIColor whiteColor];
        circle.layer.cornerRadius = 5;
        circle.layer.borderWidth = 2;
        circle.layer.borderColor = _lineChartBackgroundColor2.CGColor;
        circle.layer.masksToBounds = YES;
        circle.index = 1;
        circle.tag = 60000 + ((NSNumber*)self.secondYValues[i]).integerValue;
        [self addSubview:circle];
        [circle addTarget:self action:@selector(showScore:) forControlEvents:UIControlEventTouchUpInside];
       // [circle.layer addAnimation:[self moveYtime:0.5 Y:[NSNumber numberWithFloat:point.y-5] Rep:1] forKey:nil];
        circle.alpha = 0;
        [UIView animateWithDuration:0.5 animations:^{
            circle.alpha = 0.25;
        } completion:^(BOOL finished) {
            circle.alpha = 0.5;
            [UIView animateWithDuration:0.5 animations:^{
                circle.alpha = 0.75;
            } completion:^(BOOL finished) {
                circle.alpha = 1;
            }];
        }];
    }
}

//折线动画
- (void)doAnimationWithLayer:(CAShapeLayer *)layer{
    CABasicAnimation * baseAnimation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
    baseAnimation.duration = 1;
    baseAnimation.fromValue = @0.0;
    baseAnimation.toValue = @1.0;
    baseAnimation.repeatCount = 1;
    [layer addAnimation:baseAnimation forKey:@"strokeAnimation"];
}

//背景填充
- (void)drawGredientLayer{
    if (_lineChartBackgroundColor!=nil) {
        [self drawGredientLayer:self.onePointArr Colors:@[[_lineChartBackgroundColor colorWithAlphaComponent:0.8],[_lineChartBackgroundColor colorWithAlphaComponent:0]]];
    }
  
    if(_lineChartBackgroundColor2!=nil) {
        [self drawGredientLayer:self.secondPointArr Colors:@[[_lineChartBackgroundColor2 colorWithAlphaComponent:0.8],[_lineChartBackgroundColor2 colorWithAlphaComponent:0]]];
    }
   
}

- (void)drawGredientLayer:(NSArray*)pointArr Colors:(NSArray*)colors {
    CAGradientLayer *oneGradientLayer = [CAGradientLayer layer];
    oneGradientLayer.frame = CGRectMake(0, 0, self.contentSize.width, self.bounds.size.height); //self.bounds;
    
    UIColor *color1 = colors.firstObject;
    UIColor *color2 = colors.lastObject;
    
    oneGradientLayer.colors = @[(__bridge id)color1.CGColor,(__bridge id)color2.CGColor];
    
    oneGradientLayer.locations=@[@0.0,@1.0];
    oneGradientLayer.startPoint = CGPointMake(0.0,0.0);
    oneGradientLayer.endPoint = CGPointMake(0,1);
    
    CAShapeLayer *maskLayer = [CAShapeLayer layer];
    UIBezierPath *path = [UIBezierPath bezierPath];
    [path moveToPoint:CGPointMake(0,self.height)];
    for (NSInteger i = 0; i<pointArr.count; i++) {
        CGPoint point = ((NSNumber*)pointArr[i]).CGPointValue;
        if (i==0) {
            [path moveToPoint:CGPointMake(point.x,self.height-bounceY)];
            [path addLineToPoint:point];
        } else {
            
            CGPoint from = ((NSValue*)(pointArr[i-1])).CGPointValue;
            CGPoint to = point;
            CGPoint midPoint = [self midPointBetweenPoint1:from andPoint2:to];
            [path addQuadCurveToPoint:midPoint controlPoint:[self controlPointBetweenPoint1:midPoint andPoint2:from]];
            [path addQuadCurveToPoint:to controlPoint:[self controlPointBetweenPoint1:midPoint andPoint2:to]];
        }
        
        if (i==pointArr.count-1) {
            [path addLineToPoint:CGPointMake(point.x,self.height-bounceY)];
        }
    }
    
    maskLayer.path = path.CGPath;
    oneGradientLayer.mask = maskLayer;
    
//    CABasicAnimation * baseAnimation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
//    baseAnimation.duration = 2;
//    baseAnimation.fromValue = @0.0;
//    baseAnimation.toValue = @1.0;
//    baseAnimation.repeatCount = 1;
    
    CABasicAnimation *fadeAinmation = [CABasicAnimation animationWithKeyPath:@"locations"];
    fadeAinmation.delegate = self;
    fadeAinmation.fromValue = @[@(-0.2), @(-0.1),@(0)];
    fadeAinmation.toValue = @[@(1.0),@(1.1),@(1.2)];
    fadeAinmation.duration = 0.8;
    [oneGradientLayer addAnimation:fadeAinmation forKey:nil];
    
    [self.layer addSublayer:oneGradientLayer];
}

#pragma mark - 绘制图表
- (void)setXdateArr:(NSArray *)XdateArr {
    _XdateArr =XdateArr;
    for (UIView *view in self.subviews) {
        [view removeFromSuperview];
        [view.layer removeFromSuperlayer];
    }
    self.contentSize = CGSizeMake(20+50*ScalesW*_XdateArr.count, 0);
    
    CGFloat maxRight=self.contentSize.width-self.width;
    if (maxRight<0) {
        maxRight = 0;
    }
    self.contentOffset =CGPointMake(maxRight-10, 0);
    
    [self createLabelX];
    [self drawLine];
    [self drawGredientLayer];
    [self addPointCircle];
}


- (UIButton *)scoreBtn {
    if (!_scoreBtn) {
        _scoreBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 30*ScalesW, 19*ScalesW)];
        [_scoreBtn setBackgroundImage:[UIImage imageNamed:@"LS-词汇量标签"] forState:UIControlStateNormal];
        _scoreBtn.userInteractionEnabled = NO;
        _scoreBtn.titleLabel.font = [UIFont systemFontOfSize:10*ScalesW];
        [_scoreBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _scoreBtn.titleEdgeInsets = UIEdgeInsetsMake(-3*ScalesW, 0, 3*ScalesW, 0);
        _scoreBtn.alpha = 0;
        [self addSubview:_scoreBtn];
    }
    return _scoreBtn;
}

- (void)showScore:(LSCircleBtn*)sender {
    self.scoreBtn.centerX = sender.centerX;
    self.scoreBtn.y = sender.y-19*ScalesW;
    self.scoreBtn.alpha = 1;
    if (sender.index==0) {
        NSString *score = [NSString stringWithFormat:@"%ld",sender.tag-40000];
        [self.scoreBtn setTitle:score forState:UIControlStateNormal];
    } else {
        NSString *score = [NSString stringWithFormat:@"%ld",sender.tag-60000];
        [self.scoreBtn setTitle:score forState:UIControlStateNormal];
    }
}

#pragma mark =====横向、纵向移动===========
-(CABasicAnimation *)moveYtime:(float)time Y:(NSNumber *)y Rep:(float)repeatTimes
{
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"transform.translation.y"];///.y的话就向下移动。
    animation.toValue = y;
    animation.duration = time;
    animation.removedOnCompletion = NO;//yes的话，又返回原位置了。
    animation.repeatCount = repeatTimes;
    animation.fillMode = kCAFillModeForwards;
    return animation;
}

#pragma mark - 动画停止
- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag {
    if(flag) {
        //[self addPointCircle];
    }
}


@end

@implementation LSCircleBtn

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        
    }
    return self;
}

- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event {
    //当前btn大小
    CGRect btnBounds = self.bounds;
    //扩大点击区域，想缩小就将-10设为正值
    btnBounds = CGRectInset(btnBounds, -10, -10);
    
    //若点击的点在新的bounds里，就返回YES
    return CGRectContainsPoint(btnBounds, point);
}

@end
